
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'

import {Users}  from './data/user'
import {Books}  from './data/book'

let _Users = Users;
let _Books = Books;

export default{
	init () {
		let mock  = new MockAdapter(axios)
		mock.onGet('/success').reply(200, {
	      msg: 'success'
	    })
	
	    mock.onGet('/error').reply(500, {
	      msg: 'failure'
	    })
	    //用户列表
		mock.onGet('/a/Apage1').reply(config =>{
			let name = config.params.name;
			let addr = config.params.addr;
			let birth = config.params.birth;
			
			let mockUsers = _Users.filter(user => {
		        if (name && user.name.indexOf(name) === -1 || addr && user.addr.indexOf(addr) === -1|| birth && user.birth.indexOf(birth) === -1) return false
		        return true
		    })
			return new  Promise((resolve,reject)=>{
				setTimeout(()=>{
					resolve([200,{
						users:mockUsers
					}])
				}, 500)
			})
		})
		//图书列表
		mock.onGet('/a/Apage4').reply(config =>{
			/*let page = config.params.page
			let name = config.params.name;
			let addr = config.params.addr;
			let birth = config.params.birth;*/
			let {page,name,addr,birth} =  config.params;
			let mockBooks = _Books.filter(user => {
		        if (name && user.name.indexOf(name) === -1 || addr && user.addr.indexOf(addr) === -1|| birth && user.birth.indexOf(birth) === -1) return false
		        return true
		    })
			let total = mockBooks.length;
			mockBooks = mockBooks.filter((u, index) => index < 10 * page && index >= 10 * (page - 1))
			return new  Promise((resolve,reject)=>{
				setTimeout(()=>{
					resolve([200,{
						users:mockBooks,
						total:total,
					}])
				}, 500)
			})
		})
		
		// 新增图书
	    mock.onGet('/book/add').reply(config => {
	      let {name, birth, addr} = config.params
	      _Books.push({
	        name: name,
	        birth: birth,
	        addr: addr,
	      })
	      return new Promise((resolve, reject) => {
	        setTimeout(() => {
	          resolve([200, {
	            code: 200,
	            msg: '新增成功'
	          }])
	        }, 500)
	      })
	    })
	    
	    //删除用户
	    mock.onGet('/book/delete').reply(config=>{
	    	let{id} = config.params;
	    	_Books = _Books.filter ( b =>b.id !==id)
	    	return new　Promise((resolve,reject)=>{
	    		setTimeout(()=>{
	    			resolve([200,{
	    				code:200,
	    				msg:'删除成功'
	    			}])
	    		},500)
	    	})
	    })
	    
	   
	    mock.onGet('/book/edit').reply(config=>{
		    	let { id,name, birth , addr } = config.params
		    	_Books.some( u=>{
		    		if(u.id ===id){
		    			u.name = name
			    		u.birth = birth
			    		u.addr = addr
			    		return   true
		    		}
		    	})
		    	return new Promise((resolve,reject)=>{
		    		setTimeout(()=>{
		    			resolve([200,{
							code:200,
							msg:'编辑成功'
			    		}])
		    	},500)
		    })
		})
	}    
	
}
